package cn.edu.cuit.mockfns.fam.processors;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;

import cn.edu.cuit.mockfns.BusinessLogic;
import cn.edu.cuit.mockfns.fam.tuples.Event;

public class InternalDefaultCommunicator
    implements Communicator
{
    private static Map<Integer, InternalDefaultCommunicator> communicatorMap;

    private LinkedBlockingDeque<Event<?>> eventQueue;
    private Integer jobIdentity;

    static
    {
        communicatorMap = new HashMap<Integer, InternalDefaultCommunicator>();
    }

    private InternalDefaultCommunicator()
    {
        eventQueue = new LinkedBlockingDeque<Event<?>>();
    }

    public static InternalDefaultCommunicator getInstanceForCurrentJob( Object jobId )
    {
        InternalDefaultCommunicator communicator;

        if( ( communicator = communicatorMap.get( jobId ) ) == null )
        {
            communicator = new InternalDefaultCommunicator();
            communicatorMap.put( (Integer) jobId, communicator );
        }

        return communicator;
    }

    @Override
    public void send( Event<?> event, Object jobIdentity )
    {
        eventQueue.add( event );
        jobIdentity = (Integer) jobIdentity;
    }

    @Override
    public Event<?> recieve()
    {
        // TODO Auto-generated method stub
        Event<?> event = eventQueue.poll();
        ( (BusinessLogic) ( JobPool.findCurrentJob( jobIdentity ).getJobObject() ) ).comsume( event );
        return event;
    }
}
